package com.zmn.plat.admin.controller.servcategory;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.com.google.common.base.Joiner;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.business.interfaces.servcategory.ServAssCategoryBService;
import com.zmn.plat.common.dictionary.BaseAcceptProjectTypeEnum;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.common.util.StringToArrayUtil;
import com.zmn.plat.model.entity.base.acceptproject.AcceptProject;
import com.zmn.plat.model.entity.base.phenomenon.Phenomenon;
import com.zmn.plat.model.entity.base.servicecontent.ServiceContent;
import com.zmn.plat.model.entity.servcategory.ServAssCategory;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author duanzuocai
 * @version v1.0
 * @类说明：服务分类、产品分类关联功能
 * @since 2018/10/20 9:15
 */
@Controller
@RequestMapping("/serv/categ/ass/")
public class ServAssCategoryModifyController extends ServCategoryBaseController {
    private final Logger logger = LoggerFactory.getLogger(ServAssCategoryModifyController.class);

    @Autowired
    private ServAssCategoryBService servAssCategoryBService;

    @RequestMapping(value = "create")
    @ResponseBody
    public ResponseDTO create(HttpServletRequest request, @RequestParam(value = "servCategId", defaultValue = "0") Integer servCategId,
                              @RequestParam(value = "categOneId", defaultValue = "0") Integer categOneId,
                              @RequestParam(value = "categId", defaultValue = "0") Integer categId) {
        if (servCategId < 1 || categOneId < 1 || categId < 1) {
            return ResponseDTO.fail("请检查参数是否正确！");
        }

        ServAssCategory ass = new ServAssCategory();
        ass.setServCategId(servCategId);
        ass.setCategOneId(categOneId);
        ass.setCategId(categId);

        ass.setCreater(getMcStaffRealName());
        ass.setCreateTime(DateUtil.getNow());

        try {
            servAssCategoryService.insert(ass);
        } catch (org.springframework.dao.DuplicateKeyException ex) {
            logger.error("关联已经存在，不能重复添加！");
            return ResponseDTO.fail("关联已经存在，不能重复添加！");
        } catch (Exception e) {
            logger.error("添加关联异常 异常信息：{}！", e);
            return ResponseDTO.fail(e.getMessage());
        }
        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, GlobalConsts.SUCCESS_MSG);
    }

    @PostMapping(value = "batchAddAssociation")
    @ResponseBody
    public ResponseDTO batchAddAssociation(HttpServletRequest request, @RequestBody JSONObject object) {
        if (null == object) {
            return ResponseDTO.fail("请检查参数是否正确！");
        }

        try {
            servAssCategoryBService.batchAddAssociation(getMcStaffRealName(), object);
            return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "提交成功");
        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        } catch (Exception e) {
            logger.error("batchAddAssociation error..", e);
            return ResponseDTO.fail("提交失败");
        }

    }

    /**
     * 修改产品分类关联的产品组
     */
    @RequestMapping("updateBizTypeGroup")
    @ResponseBody
    @RequiresPermissions("/serv/categ/ass/updateBizTypeGroup.action")
    public ResponseDTO updateBizTypeGroup(HttpServletRequest request, @RequestBody ServAssCategory servAssCategory) {

        Date now = DateUtil.getNow();
        int groupId = servAssCategory.getGroupId();

        try {
            if (NumberUtil.isNullOrZero(groupId)) {
                return ResponseDTO.fail("主键不能为空！");
            }

            servAssCategory.setUpdater(getMcStaffRealName());
            servAssCategory.setUpdateTime(now);

            boolean flag = NumberUtil.isNullOrZero(servAssCategory.getPerProductGroupbId())
                    && NumberUtil.isNullOrZero(servAssCategory.getPerProductGroupcId())
                    && NumberUtil.isNullOrZero(servAssCategory.getPerProductGroupfId());
            if (flag) {
                servAssCategory.setPerTime(null);
            }

            if (Objects.nonNull(servAssCategory.getPerTime())) {
                // 判断时间是否小于当前时间，小于当前时间立即生效 小于-1
                Integer preTime = DateUtil.getNow().compareTo(servAssCategory.getPerTime());
                if (preTime >= 0) {
                    setValue(servAssCategory);
                    servAssCategoryService.updateBizTypeGroup(servAssCategory);
                    return ResponseDTO.success(true, "操作成功！");
                } else {
                    servAssCategory.setPerTime(DateUtil.getDateStart(servAssCategory.getPerTime()));
                }
            }

            if (!flag && Objects.isNull(servAssCategory.getPerTime())) {
                servAssCategory.setPerTime(DateUtil.getDateStart(DateUtil.getNowDefer(1)));
            }

            servAssCategoryService.updatePerBizTypeGroup(servAssCategory);

            return ResponseDTO.success(true, "操作成功！");
        } catch (Exception e) {
            logger.error("新增/修改失败,Exception{},msg{}", e, e.getMessage());
            return ResponseDTO.fail("操作失败！");
        }
    }

    @RequiresPermissions("/serv/categ/ass/delete.action")
    @RequestMapping(value = "delete")
    @ResponseBody
    public ResponseDTO delete(@RequestParam(value = "ids", defaultValue = "0") String groupIds) {
        if (StringUtils.isEmpty(groupIds)) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择要删除的数据！");
        }

        showCategoryAssociationService.deleteByShowServCategIdAndShowCategOneIdAndShowCategId(groupIds.split(","));
        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
    }

    @RequestMapping(value = "updateDesc")
    @ResponseBody
    public ResponseDTO updateDesc(@RequestParam(value = "id") Integer id, @RequestParam(value = "desc") String desc) {
        if (id == null) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择要修改的的数据！");
        }

        servAssCategoryService.updateDesc(id, desc);

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
    }

    @RequestMapping(value = "updateDisclaimer")
    @ResponseBody
    public ResponseDTO updateDisclaimer(@RequestParam(value = "id") Integer id, @RequestParam(value = "disclaimer") String disclaimer) {
        if (id == null) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择要修改的的数据！");
        }

        servAssCategoryService.updateDisclaimer(id, disclaimer, getMcStaffRealName());

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
    }

    @RequestMapping(value = "saveServiceContent")
    @ResponseBody
    public ResponseDTO saveServiceItem(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId,
                                       @RequestParam(value = "serviceContentIds", defaultValue = "0") String serviceContentIds) {
        if (groupId == null) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择要修改的的数据！");
        }
        if (StringUtil.isBlank(serviceContentIds)) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择关联的故障现象！");

        }
        final List<Integer> listServiceContent = StringToArrayUtil.convertStrsToList(serviceContentIds);
        List<ServiceContent> baseServiceContents = baseServiceItemService.listByIds(listServiceContent);
        final List<Integer> collect = baseServiceContents.stream()
                .map(ServiceContent::getServId).collect(Collectors.toList());
        final String serviceContent = Joiner.on(",").join(collect);

        servAssCategoryService.updateServiceContentByGroupId(groupId, serviceContent, getMcStaffRealName());

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
    }

    @RequestMapping(value = "saveAcceptProject")
    @ResponseBody
    public ResponseDTO saveAcceptProject(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId,
                                         @RequestParam(value = "engineerAcceptProject", defaultValue = "0") String engineerAcceptProject,
                                         @RequestParam(value = "userAcceptProject", defaultValue = "0") String userAcceptProject) {
        if (groupId == null) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择要修改的的数据！");
        }
        if (StringUtil.isBlank(engineerAcceptProject)) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择关联的工程师验收项目！");
        }
        if (StringUtil.isBlank(userAcceptProject)) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择关联的用户验收项目！");
        }
        List<Integer> listEngineerIds = StringToArrayUtil.convertStrsToList(engineerAcceptProject);
        List<Integer> listUserIds = StringToArrayUtil.convertStrsToList(userAcceptProject);

        // 根据id获取工程师验收项目和用户验收项目
        List<AcceptProject> list = baseAcceptProjectService.listByIds(ListUtils.union(listEngineerIds, listUserIds));
        if (CollectionUtil.isNullOrEmpty(list)) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "未获取到相关验收项目选项！");
        }

        // 获取工程师验收项目
        final List<Integer> collect = list.stream()
                .filter(x -> Objects.equals(x.getAcceType(), BaseAcceptProjectTypeEnum.ENGINEER_ACCEPT.getCode()))
                .map(AcceptProject::getAcceId).collect(Collectors.toList());
        final String engineer = Joiner.on(",").join(collect);

        // 获取用户验收项目
        final List<Integer> listUserAcceptProject = list.stream()
                .filter(x -> Objects.equals(x.getAcceType(), BaseAcceptProjectTypeEnum.USER_ACCEPT.getCode()))
                .map(AcceptProject::getAcceId).collect(Collectors.toList());
        final String user = Joiner.on(",").join(listUserAcceptProject);

        servAssCategoryService.updateEngineerAcceptProjectAndUserAcceptProjectByGroupId(groupId, engineer, user, getMcStaffRealName());
        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
    }

    @RequestMapping(value = "saveFauit")
    @ResponseBody
    public ResponseDTO saveFauit(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId,
                                 @RequestParam(value = "faultIds", defaultValue = "0") String faultIds) {
        if (groupId == null) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择要修改的的数据！");
        }
        if (StringUtil.isBlank(faultIds)) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择关联的故障现象！");

        }
        final List<Integer> listFaulIds = StringToArrayUtil.convertStrsToList(faultIds);

        List<Phenomenon> faultPhenomena = phenomenonService.listByIds(listFaulIds);

        final List<Integer> collect = faultPhenomena.stream().map(Phenomenon::getPhenId).collect(Collectors.toList());
        final String join = Joiner.on(",").join(collect);
        servAssCategoryService.updateFaultByGroupId(groupId, join, getMcStaffRealName());

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
    }

    @RequestMapping(value = "saveTstDrip")
    @ResponseBody
    public ResponseDTO saveTstDrip(@RequestParam(value = "groupId", defaultValue = "0") Integer groupId,
                                   @RequestParam(value = "tstDrip", defaultValue = "0") String tstDrip) {
        if (NumberUtil.isNullOrZero(groupId)) {
            return ResponseDTO.fail(StatusConsts.STATUS_ERROR, "请选择要修改的的数据！");
        }
        servAssCategoryService.updateTstDripByGroupId(groupId, tstDrip, getMcStaffRealName());

        return ResponseDTO.success(StatusConsts.STATUS_SUCCESS, "操作成功！");
    }

    private void setValue(ServAssCategory servAssCategory) {
        servAssCategory.setProductGroupbId(servAssCategory.getPerProductGroupbId());
        servAssCategory.setProductGroupcId(servAssCategory.getPerProductGroupcId());
        servAssCategory.setProductGroupfId(servAssCategory.getPerProductGroupfId());
        servAssCategory.setPerProductGroupbId(null);
        servAssCategory.setPerProductGroupcId(null);
        servAssCategory.setPerProductGroupfId(null);
        servAssCategory.setPerTime(null);
        servAssCategory.setProductGroupbName(servAssCategory.getPerProductGroupbName());
        servAssCategory.setProductGroupcName(servAssCategory.getPerProductGroupcName());
        servAssCategory.setProductGroupfName(servAssCategory.getPerProductGroupfName());
        servAssCategory.setPerProductGroupbName(null);
        servAssCategory.setPerProductGroupcName(null);
        servAssCategory.setPerProductGroupfName(null);
    }
}
